<?php

/**
 * Gestionnaire de persistance des classes métiers en BD
 *
 * @author Guy
 */
class Persistance {
   
    public static $indexTable       = "`index`";
    public static $documentTable    = "`document`";
    public static $occurenceTable   = "`occurence`";
    
    protected $db;
    protected $indexer;

    public function __construct(PDO $db) {
        $this->db       = $db;
    }

    public function getOccurences()
    {
        $stmt = $this->db->prepare("SELECT * FROM ".self::$occurenceTable);
        $stmt->execute();
        
        $occurences = array();
        foreach($stmt->fetchAll() as $row)
        {
            $occurences[] = (new Occurence)
                    ->setId($row["id"])
                    ->setBalise($row["balise"])
                    ->setDocument(getDocument($this->db, array("id" => $row["id_document"])))
                    ->setMot($row["mot"])
                    ->setTerme($row["terme"]);
        }  
        
        return $occurences;
    }

    public function deleteIndex()
    {
        $this->query("DELETE FROM ".self::$indexTable);

        return $this;
    }
    
    public function deleteAll()
    {
        $tables = array(
            self::$indexTable,
            self::$occurenceTable,
            self::$documentTable
        );
        
        foreach($tables as $table)
        {
            $this->query("DELETE FROM ".$table);
        }
        
        return $this;
    }
    
    protected function query($query)
    {
        $this->db->query($query);
        
        return $this;
    }
    
    public function persistIndexes($documentIndexes)
    {
        $stmt = $this->db->prepare("INSERT INTO ".self::$indexTable."(id_document, terme, poids) "
                . "VALUES(:id_document, :terme, :poids)");
        
        foreach($documentIndexes as $indexes)
        {
            foreach($indexes as $index)
            {
                $stmt->execute(array(
                    ":id_document"  => $index->getDocument()->getId(),
                    ":terme"        => $index->getTerme(),
                    ":poids"        => $index->getPoids()
                ));
            }
        }  
        
        return $this;
    }    
    
    public function persistOccurences($occurences)
    {
        $stmt = $this->db->prepare("INSERT INTO ".self::$occurenceTable."(id_document, mot, balise, terme) "
                . "VALUES(:id_document, :mot, :balise, :terme)");
        
        foreach($occurences as $occurence)
        {
            $stmt->execute(array(
                ":id_document"      => $occurence->getDocument()->getId(),
                ":mot"              => $occurence->getMot(),
                ":balise"           => $occurence->getBalise(),
                ":terme"            => $occurence->getTerme()
            ));
            $occurence->setId($this->db->lastInsertId());
        }
        
        return $this;
    }
    
    /**
     * 
     * @param Documents[] $documents
     * @return Persistance
     */
    public function persistLongueurDocuments($documents)
    {
        $stmt = $this->db->prepare("UPDATE ".self::$documentTable." SET longueur = :longueur WHERE id = :id_document");
        foreach($documents as $document)
        {
            $longueur = $this->getLongueurDocument($document->getId());
            
            $stmt->execute(array(
                ":longueur" => $longueur,
                ":id_document" => $document->getId()
            ));
        }
    }

    //TODO: vérifier que la longueur d'un document se determine à partir de la table des occurences
    public function getLongueurDocument($id_document)
    {
        $stmt = $this->db->prepare("SELECT COUNT(*) AS nb FROM ".self::$occurenceTable." WHERE id_document = :id_document");
        $stmt->execute(array(
            ":id_document" => $id_document
        ));
        
        return $stmt->fetch()["nb"];
    }
    
    public function persistDocuments($documents)
    {        
        $stmt = $this->db->prepare("INSERT INTO ".self::$documentTable."(path, titre, icone, description) "
                . "VALUES(:path, :titre, :icone, :description)");

        foreach($documents as $document)
        {
            $stmt->execute(array(
                ":path"         => $document->getPath(),
                ":titre"        => $document->getTitre(),
                ":icone"        => $document->getIcone(),
                ":description"  => $document->getDescription()
            ));
            
            $document->setId($this->db->lastInsertId());
        }

        return $this;
    }
}
